import fetch from '../utils/fetch';
import { message } from 'antd';
import config from '../config';
import { ADMIN_ADD } from '../actionTypes';

export const updateAdd = (payload) => ({
  type: ADMIN_ADD,
  payload,
});

export const changeName = (e) => (dispatch) => {
  dispatch(updateAdd({
    name: e.target.value,
  }));
};

export const changeType = (e) => (dispatch) => {
  dispatch(updateAdd({
    type: e.target.value,
  }));
};

export const changeAvatar = (e) => (dispatch) => {
  dispatch(updateAdd({
    avatar: e.target.value,
  }));
};

export const change = (e, obj) => (dispatch, getState) => {
  const { add } = getState().admin;
  const content = [...add.content] || [];
  const index = content.findIndex(item => item.id === obj.id);
  const val = {
    ...obj,
    content: e.target.value,
  };
  if (index === -1) {
    content.push(val);
  } else {
    content.splice(index, 1, val);
  }
  dispatch(updateAdd({
    content,
  }));
};

export const del = (obj) => (dispatch, getState) => {
  const { add } = getState().admin;
  const content = [...add.content] || [];
  const index = content.findIndex(item => item.id === obj.id);
  content.splice(index, 1);
  dispatch(updateAdd({
    content,
  }));
};

export const submit = (cb) => async (dispatch, getState) => {
  const { add } = getState().admin;
  const { name, type, avatar, content } = add;
  if (content.length === 0) {
    message.error('至少添加一条');
    return false;
  }
  const addRes = await fetch({
    method: 'post',
    url: `${config.HOST}/admin/lesson/add`,
    param: {
      name,
      type,
      avatar,
      content,
    },
  });
  if (addRes.code === 200) {
    cb(addRes.data);
    message.success('添加课程成功');
  } else {
    message.error('添加课程失败');
  }
};
